﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Bll;
using Model;
using System.Data;
using System.Net;
using System.IO;
using System.Text;

namespace Accounting.admin.DPD
{
    public partial class DepartmentAdd : System.Web.UI.Page
    {
        BllPublic b = new BllPublic();
        ModelPublic m = new ModelPublic();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                if (Session["Name"] != null && Session["Type"] != null)
                {
                    txtAuthor.Text = Session["Name"].ToString();

                    dataBind();
                    UserType.Text = Session["Type"].ToString();
                    txtDateTime.Text = DateTime.Now.ToString("yyyy-MM-dd");

                    if (UserType.Text == "0")
                    {
                        Release.Visible = true;
                    }
                    else
                    {
                        Release.Visible = false;
                    }
                }
                else
                {
                    btnRest.Enabled = false;
                    ASubmit.Disabled = false;
                }
            }
        }

        public void dataBind()
        {
            m.NavId = "2";
            DataTable dt = b.SubNav_Inquire_All(m);
            foreach (DataRow my in dt.Rows)
            {
                string name = "--" + my["Name"].ToString() + "--";
                string id = my["Id"].ToString();
                NavSubList.Items.Add(new ListItem(name, id));
            }

            DataTable nav = b.Nav_Inquire_All();

            foreach (DataRow my in nav.Rows)
            {
                if (my["Id"].ToString() == "2")
                {
                    H2_Title.InnerText = "添加：" + my["Name"].ToString();
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string folderRouteImg = "";
            string folderRouteFile = "";

            m.NavSubId ="'"+ NavSubList.SelectedValue + "'";
            m.Title = "'" + txtTitle.Text.Trim() + "'";
            m.DateTime = "'" + txtDateTime.Text.Trim() + "'";
            m.Author = "'" + txtAuthor.Text.Trim() + "'";
            m.NavSubId = "'" + NavSubList.SelectedValue + "'";
            m.Content = Content.Text ;
            m.Number = "'" + txtNumber.Text.Trim() + "'";
            m.NavId = "'2'";

            if (Recommend.Checked == true)
            {
                m.Recommend = "'True'";

                if (RecommendFile.HasFile)
                {
                    //推荐图片上传
                    string Upname = RecommendFile.FileName;

                    int Pointposition = 0;
                    string FileName = "";
                    string suffix = "";

                    for (int i = 0; i < Upname.Length; i++)
                    {
                        if (Upname[i] == '.')
                        {
                            Pointposition = i;
                            break;
                        }
                    }

                    for (int i = 0; i < Pointposition; i++)
                    {
                        FileName += Upname[i];
                    }

                    for (int i = Pointposition; i < Upname.Length; i++)
                    {
                        suffix += Upname[i];
                    }

                    m.DateTime = txtDateTime.Text.Trim();

                    int num = b.Information_Count_Img_Number(m);

                    string Time = System.DateTime.Now.ToString("yyyyMMdd");
                    folderRouteImg = "images/Recommend/" + Time +2+ (num + 1).ToString() + suffix;

                    m.RecommendRoute = "'" + folderRouteImg + "'";
                    m.RecommendName = "'" + RecommendFile.FileName + "'";

                }
                else
                {
                    m.RecommendRoute = "NULL";
                    m.RecommendName = "NULL";
                }

            }
            else
            {
                m.RecommendRoute = "NULL";
                m.RecommendName = "NULL";

                m.Recommend = "'False'";

            }

            if (UserType.Text == "0")
            {
                m.Remarks = "NULL";
                if (Release.Checked == true)
                    m.Release = "'True'";
                else
                    m.Release = "'False'";
            }
            else
            {
                m.Remarks = "'stu'";
                m.Release = "'false'";
            }

            if (ReleaseFile.HasFile)
            {
                string Upname = ReleaseFile.FileName;

                int Pointposition = 0;
                string FileName = "";
                string suffix = "";

                for (int i = 0; i < Upname.Length; i++)
                {
                    if (Upname[i] == '.')
                    {
                        Pointposition = i;
                        break;
                    }
                }

                for (int i = 0; i < Pointposition; i++)
                {
                    FileName += Upname[i];
                }

                for (int i = Pointposition; i < Upname.Length; i++)
                {
                    suffix += Upname[i];
                }

                m.DateTime = txtDateTime.Text.Trim();

                int num = b.Information_Count_File_Number(m);

                string Time = System.DateTime.Now.ToString("yyyyMMdd");
                folderRouteFile = "InformationFile/" + Time +2+ (num + 1).ToString() + suffix;

                m.FileName = "'" + ReleaseFile.FileName + "'";
                m.FileRoute = "'" + folderRouteFile+"'";
            }
            else
            {
                m.FileName = "NULL";
                m.FileRoute = "NULL";
            }




            string message = b.Information_Add(m);
            if (message == "1")
            {
                Response.Write("<script>alert('添加成功！')</script>");

                //推荐图片上传
                if(RecommendFile.HasFile)
                {
                    try
                    {
                        RecommendFile.SaveAs(Server.MapPath("../../" + folderRouteImg));
                    }
                    catch (Exception ex)
                    {
                        Response.Write("<script>alert('上传失败:" + ex.Message + "')</script> ");
                    }
                }

                //文件上传
                if(ReleaseFile.HasFile)
                {
                    try
                    {
                        ReleaseFile.SaveAs(Server.MapPath("../../" + folderRouteFile));
                    }
                    catch (Exception ex)
                    {
                        Response.Write("<script>alert('上传失败:" + ex.Message + "')</script> ");
                    }
                }

                //发送到公共信息
                m.Title = txtTitle.Text.Trim();
                m.NavId = "2";
                string id = b.Information_Id(m);
                AddNews(id);
            }
            else
            {
                Response.Write("<script>alert('" + message + "')</script>");
            }

        }

        private void ContentVerification(string message)
        {
            Response.Write("<script>alert('" + message + "')</script>");
        }

        protected void btnRest_Click(object sender, EventArgs e)
        {
            ClearContext();
        }

        private void ClearContext()
        {
            txtAuthor.Text = "";
            txtDateTime.Text = "";
            txtNumber.Text = "";
            txtTitle.Text = "";
            Content.Text = "";
            NavSubList.SelectedIndex = -1;
        }

        private void AddNews(string id)
        {
            string stid = Request["stid"];//信息公开网站相应的类别
            string stracc = "ckuivf";
            string strpwd = "fcsaezxcbn3d";


            string istb = Request.Params["istb"];//
            if (!string.IsNullOrEmpty(istb))
            {
                Adddate(id, stid, txtTitle.Text.Trim(), null, txtDateTime.Text.Trim(), Content.Text, stracc, strpwd, "http://xxgk.wzvtc.cn/data/adddata");
            }
        }

        public string Adddate(string id, string stid, string title, string ctitle, string postdate, string Article, string unames, string upass, string url)
        {


            string requestBody = string.Format("iid={0}&tid={1}&title={2}&TitleColor={3}&postdate={4}&Article={5}&unames={6}&upass={7}"

               , HttpUtility.UrlEncode(id, Encoding.GetEncoding("utf-8"))
               , HttpUtility.UrlEncode(stid, Encoding.GetEncoding("utf-8"))
               , HttpUtility.UrlEncode(title, Encoding.GetEncoding("utf-8"))
               , HttpUtility.UrlEncode(ctitle, Encoding.GetEncoding("utf-8"))
               , HttpUtility.UrlEncode(postdate, Encoding.GetEncoding("utf-8"))
               , HttpUtility.UrlEncode(Article, Encoding.GetEncoding("utf-8"))
                , HttpUtility.UrlEncode(unames, Encoding.GetEncoding("utf-8"))
                  , HttpUtility.UrlEncode(upass, Encoding.GetEncoding("utf-8"))
               , string.Empty
                );
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.KeepAlive = false;
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] aryBuf = Encoding.GetEncoding("utf-8").GetBytes(requestBody);
            request.ContentLength = aryBuf.Length;
            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(aryBuf, 0, aryBuf.Length);
                writer.Close();
                writer.Dispose();
            }
            string ret = string.Empty;
            using (WebResponse response = request.GetResponse())
            {
                StreamReader reader = new StreamReader(response.GetResponseStream()
                    , Encoding.GetEncoding("utf-8")
                    );
                ret = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();
            }

            return ret;
        }
    }
}